package com.kernowsoft.wavefx;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.kernowsoft.wavefx.R;
import com.kernowsoft.wavefx.WaveDataContentProvider.SiteForecast;

public class WaveFxListActivity extends FragmentActivity {

	public static final String TAG = WaveFxListActivity.class.getSimpleName();
	
	// member variables:
	private String mStrLocation = "Croyde";
	private ArrayList<String> mStrLocations = new ArrayList<String>();
	private HashMap<String, Date> mValidTimes;

	// views:
	private WaveFxListFragment mFxListView;
	private ProgressDialog mProgressDlg;

	// menu IDs
	private final int MENU_GROUP_LOCATIONS = Menu.FIRST;

	private ResponseReceiver mReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.wave_fx_list);
		mProgressDlg = new ProgressDialog(this);
		mProgressDlg.setMessage("Loading data");
		mProgressDlg.setIndeterminate(false);
		mProgressDlg.setMax(100);
		mProgressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDlg.dismiss();

		mFxListView = (WaveFxListFragment) getSupportFragmentManager()
				.findFragmentById(R.id.wave_fx_list);
		setNewLocation("Croyde");
		mFxListView.setSite(mStrLocation);
		
		// reload saved variables
		if(savedInstanceState != null) {
			mValidTimes = (HashMap<String,Date>)savedInstanceState.getSerializable("validtimes");
		}
		

		// hardcode some default locations: TODO: Get from saved settings.
		// TODO: Sites will be requested via SiteSelectorActivity
		mStrLocations.add("Croyde");
		mStrLocations.add("Perran");
		mStrLocations.add("Mountsbay");
		mStrLocations.add("Ekofisk");

		// instantiate broadcast receiver:
		mReceiver = new ResponseReceiver();
		IntentFilter filter = new IntentFilter(ForecastUpdateService.FX_UPDATED);
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		registerReceiver(mReceiver, filter);
	}

	@Override
	// @SuppressLint("NewApi")
	public boolean onCreateOptionsMenu(Menu menu) {
		// to add to the action bar, use the inflater
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_fx_list, menu);

		// add sites
		Menu sitemenu = menu.findItem(R.id.menu_change_location).getSubMenu();

		sitemenu.clear();
		Iterator<String> i = mStrLocations.iterator();
		while (i.hasNext()) {
			String site = i.next();
			Log.i(TAG, "Adding " + site + " to menu " + sitemenu.toString());
			sitemenu.add(MENU_GROUP_LOCATIONS, Menu.NONE, Menu.NONE, site);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent;
		
		switch (item.getItemId()) {
		case R.id.menu_change_location:
			return true;

		case R.id.menu_fx_list_refresh:
			// could handle this here, if we wanted:
			/*
			 * Toast.makeText(this, "Activity got menu selection: " +
			 * item.getTitle(), Toast.LENGTH_SHORT).show(); return true;
			 */

		case R.id.menu_addsite:
			intent = new Intent();
			intent.setClass(this, SiteSelectorActivity.class);
			int requestCode = 999;
			startActivityForResult(intent, requestCode);
			return true;
			
		case R.id.menu_refesh:
			// refresh the current forecast:
			intent = new Intent(this, ForecastUpdateService.class);
			intent.setAction(ForecastUpdateService.REQUEST_FX_UPDATE);
			intent.putExtra(ForecastUpdateService.SITE_NAME, mStrLocation);	
			startService(intent);
			return true;
		}

		if (item.getGroupId() == MENU_GROUP_LOCATIONS) {
			setNewLocation(item.getTitle().toString());	
			return true;
		}

		Toast.makeText(
				this,
				"Unhlandled menu item: " + item.getTitle() + " ("
						+ item.getItemId() + ")", Toast.LENGTH_SHORT).show();

		return false;
	}

	public void setNewLocation(String location) {
		mStrLocation = location;

		// update site text:
		((TextView) findViewById(R.id.wave_fx_view_sitename))
				.setText(mStrLocation);
		
		// update list in list view
		mFxListView.setSite(mStrLocation);
	}

	
	private class ResponseReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String site = intent
					.getStringExtra(ForecastUpdateService.SITE_NAME);
			Log.d(TAG, "Recieved broadcast, fx update for " + site);

			// update validity time of forecast
			String projection[] = new String[] {WaveDataContentProvider.SiteForecast.VALID_DATETIME};
			String selection = SiteForecast.SITENAME + " = '" + site + "'";
			String selectionArgs[] = null;
			String sortOrder = null;
			Log.d(TAG, "Getting new validity time of forecast");
			Cursor c = getContentResolver().query(WaveDataContentProvider.SiteForecast.VALIDTIME_URI,
					projection, selection, selectionArgs, sortOrder);
			if(c.moveToFirst()) {
				String validtime = c.getString(0);
				((TextView) findViewById(R.id.wave_fx_view_sitename))
				.setText(mStrLocation + " @ " + validtime);
			} else
				Log.d(TAG, "No valid times in database....");
		}
	}
}
